<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件


use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;

/**
 * 获取系统配置
 */
function get_site_config()
{
	$config=cache('siteconfig');
	if(empty($config))
	{
		$config=Db::name('admin_config',[],false)->select();
		cache('siteconfig',$config);
	}
	if(!empty($config))
	{
		foreach($config as $k=>$v)
		{
			if($v['status'])config($v['name'],$v['value']);

		}
	}
	return 1;
}

/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start = 0, $length,$suffix = true,$charset = "utf-8") {
	if (function_exists("mb_substr")) {
		$slice = mb_substr($str, $start, $length, $charset);
	} elseif (function_exists('iconv_substr')) {
		$slice = iconv_substr($str, $start, $length, $charset);
		if (false === $slice) {
			$slice = '';
		}
	} else {
		$re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("", array_slice($match[0], $start, $length));
	}
	if (strlen($slice) == strlen($str)) {
		return $slice;
	} else {
		return $suffix ? $slice . '...' : $slice;
	}
}

/**
* 验证手机号是否正确
* @param number $mobile
*/
function check_mobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}
/**
 * 验证邮箱是否合法
 * @param string $email
 */
function check_email($email){
 	if (preg_match('/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/',$email)){
		return true;
 	}else{
		return false;
	}
}
/**
 * 判断身份证有效性的
 */
function check_idcard($number) {
   $vCity = array(
        '11','12','13','14','15','21','22',
        '23','31','32','33','34','35','36',
        '37','41','42','43','44','45','46',
        '50','51','52','53','54','61','62',
        '63','64','65','71','81','82','91'
    );
    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $number)) return false;
    if (!in_array(substr($number, 0, 2), $vCity)) return false;
    $number = preg_replace('/[xX]$/i', 'a', $number);
    $vLength = strlen($number);
    if ($vLength == 18)
    {
        $vBirthday = substr($number, 6, 4) . '-' . substr($number, 10, 2) . '-' . substr($number, 12, 2);
    } else {
        $vBirthday = '19' . substr($number, 6, 2) . '-' . substr($number, 8, 2) . '-' . substr($number, 10, 2);
    }
    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
    if ($vLength == 18)
    {
        $vSum = 0;
        for ($i = 17 ; $i >= 0 ; $i--)
        {
            $vSubStr = substr($number, 17 - $i, 1);
            $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
        }
        if($vSum % 11 != 1) return false;
    }
    return true;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false) {
	$type      = $type ? 1 : 0;
	static $ip = NULL;
	if ($ip !== NULL) {
		return $ip[$type];
	}
	if ($adv) {
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			$pos = array_search('unknown', $arr);
			if (false !== $pos) {
				unset($arr[$pos]);
			}

			$ip = trim($arr[0]);
		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} elseif (isset($_SERVER['REMOTE_ADDR'])) {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
	} elseif (isset($_SERVER['REMOTE_ADDR'])) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	// IP地址合法验证
	$long = sprintf("%u", ip2long($ip));
	$ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
	return $ip[$type];
}


/**
 * 获取分类所有子分类
 * @param int $cid 分类ID
 * @return array|bool
 */
function get_category_children($cid)
{
    if (empty($cid)) {
        return false;
    }

    $children = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->select();

    return array2tree($children);
}

/**
 * 根据分类ID获取文章列表（包括子分类）
 * @param int   $cid   分类ID
 * @param int   $limit 显示条数
 * @param array $where 查询条件
 * @param array $order 排序
 * @param array $filed 查询字段
 * @return bool|false|PDOStatement|string|\think\Collection
 */
function get_articles_by_cid($cid, $limit = 10, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'cid', 'title', 'introduction', 'thumb', 'reading', 'publish_time'], (array)$filed);
    $map    = array_merge(['cid' => ['IN', $ids], 'status' => 1, 'publish_time' => ['<= time', date('Y-m-d H:i:s')]], (array)$where);
    $sort   = array_merge(['is_top' => 'DESC', 'sort' => 'DESC', 'publish_time' => 'DESC'], (array)$order);

    $article_list = Db::name('article')->where($map)->field($fileds)->order($sort)->limit($limit)->select();

    return $article_list;
}

/**
 * 根据分类ID获取文章列表，带分页（包括子分类）
 * @param int   $cid       分类ID
 * @param int   $page_size 每页显示条数
 * @param array $where     查询条件
 * @param array $order     排序
 * @param array $filed     查询字段
 * @return bool|\think\paginator\Collection
 */
function get_articles_by_cid_paged($cid, $page_size = 15, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'cid', 'title', 'introduction', 'thumb', 'reading', 'publish_time'], (array)$filed);
    $map    = array_merge(['cid' => ['IN', $ids], 'status' => 1, 'publish_time' => ['<= time', date('Y-m-d H:i:s')]], (array)$where);
    $sort   = array_merge(['is_top' => 'DESC', 'sort' => 'DESC', 'publish_time' => 'DESC'], (array)$order);

    $article_list = Db::name('article')->where($map)->field($fileds)->order($sort)->paginate($page_size);

    return $article_list;
}

/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }

    return $list;
}

/**
 * 构建层级（树状）数组
 * @param array  $array          要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name       父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int   $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name)
{
    $result = false;
    if (is_dir($dir_name)) {
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}

/**
 * 判断是否为手机访问
 * @return  boolean
 */
function is_mobile()
{
    static $is_mobile;

    if (isset($is_mobile)) {
        return $is_mobile;
    }
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $is_mobile = false;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
    ) {
        $is_mobile = true;
    } else {
        $is_mobile = false;
    }

    return $is_mobile;
}

function detectDevice() {
    if(empty($_SERVER['HTTP_USER_AGENT'])){
        return 'iOS';
    }
    $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);

    // 检测iOS设备
    if (strpos($userAgent, 'iphone') !== false ||
        strpos($userAgent, 'ipod') !== false) {
        return 'iOS';
    } elseif (strpos($userAgent, 'ipad') !== false) {
        return 'iOS';
    }

    // 检测Android设备
    if (strpos($userAgent, 'android') !== false) {
        // 区分Android手机和平板
        if (strpos($userAgent, 'mobile') !== false) {
            return 'Android';
        } else {
            return 'Android';
        }
    }

    // 检测Windows Phone
    if (strpos($userAgent, 'windows phone') !== false) {
        return 'Windows Phone';
    }

    // 其他移动设备
    if (strpos($userAgent, 'blackberry') !== false ||
        strpos($userAgent, 'bb10') !== false) {
        return 'Wap';
    }

    // 默认返回PC
    return 'Wap';
}

/**
 * 获取代理信息
 */
function get_agent($id,$field){
    $data = DB::connect('db_config_aiqi')->name('gameagent')
        ->field($field)
        ->where(array('aid'=>$id))
        ->find();
    return $data[$field];
}

/**
 * 取得代理游戏
 */
function get_agent_game(){
//    $data = DB::name('gamelist')
    $data = DB::connect('db_config_aiqi')->name('gamelist')
        ->where(array('gstatus'=>1))
        ->order("id desc")
        ->select();
    return $data;
}


/**
 *
 */
function getGameAgent($cid,$gid,$field='*')
{
    $gameArgnet = DB::connect('db_config_aiqi')->name('gameagent')
        ->field($field)
        ->where(['cid'=>$cid,'gid'=>$gid,'status'=>1])
        ->find();
    if($field == '*'){
        return $gameArgnet;
    }
    if(count(explode(',',$field)) > 1){
        return $gameArgnet;
    }
    if($field == 'extdata'){
        return json_decode($gameArgnet['extdata'],true);
    }

    return $gameArgnet[$field];
}

/**
 *
 */
function getGameAgentList()
{
    $where[] = ['a.cid','>',5];
    $where[] = ['a.status','=',1];

    $gameArgnet = DB::connect('db_config_aiqi')->name('gameagent')->alias('a')
        ->join('gamelist b', 'a.gid = b.id', 'left')
        ->where($where)
        ->field('b.id, b.name')
        ->group("gid")
        ->order('a.id DESC')
        ->select();
    return $gameArgnet;
}
/**
 * 取得游戏表字段
 */
function get_game_filed($id,$field){
    $redis = new Redis();
    $redis->select(4);
    $game = $redis->get('game_'.$id);
    if(empty($game)){
        $game = DB::connect('db_config_aiqi')->name('gamelist')
            ->where(array('id'=>$id))
            ->find();
        $redis->set('game_'.$id,$game);
        return $game[$field];
    }

    return $game[$field];
}

function get_game_notify($gid,$cid)
{
    return $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/v1/api/notify/game/pay_notify/".$gid.'/'.$cid;
}
/**
 * 取得游戏表字段
 */
function get_server_filed($id,$field){
    $data = DB::connect('db_config_aiqi')->name('gamearea')
        ->where(array('status'=>1))
        ->find();
    return $data[$field];
}

/**
 * 取得游戏list
 */
function get_game_list(){
//    $data = DB::name('gamelist')
    $data = DB::connect('db_config_aiqi')->name('gamelist')
        ->field('id,name')
//        ->where(array('gstatus'=>1))
        ->whereIn('gstatus',[1,2])
        ->order("id desc")
        ->select();
    return $data;
}

/**
 * 获取cplist
 * @return array
 */

function get_cp_list(){
    $redis = new Redis();
    $redis->select(3);
    $data = $redis->get('cp_list');
    $data = [];
    if(empty($data)){
        $data = DB::connect('db_config_aiqi')->name('cp_channel')
            ->field('id,name')
            ->order("id desc")
            ->select();
        $redis->set('cp_list',$data,3600);
    }
    return $data;
}

/**
 * 获取cp名称
 * @return string
 */
function get_cp_name($id){
    if((int) $id){
        $data = DB::connect('db_config_aiqi')->name('cp_channel')
            ->find($id);
        return !empty($data) && $data['name'] ? $data['name'] : '未知CP';
    }
    return $id;
}

function get_channel_list()
{
    $data = DB::connect('db_config_aiqi')->name('channel')
        ->field('id,platform')
        ->where(array('status'=>1))
        ->select();
    return $data;
}
function get_channel_name($id)
{
    $data = DB::connect('db_config_aiqi')->name('channel')
        ->field('id,platform')
        ->where(array('id'=>$id,'status'=>1))
        ->find();
    return $data['platform'] ?? '系统';
}
function get_user_info($id){
    $data = DB::connect('db_config_aiqi')->name('userinfo');
}

function get_player($id,$field){
    $redis = new Redis();
    $redis->select(2);
    $data = $redis->get($id);
    if(empty($data)){
        $player_old = DB::connect('db_config_aiqi')->name('jinling_palyer')->where(['old_id'=>$id])->find();
        if(!empty($player_old)){
            $data = DB::connect('db_config_aiqi')->name('player')
                ->where(array('account'=>'g_'.$player_old['gd_id'],'status'=>1))
                ->find();
        }else{
            $data = DB::connect('db_config_aiqi')->name('player')
                ->where(array('id'=>$id,'status'=>1))
                ->find();
        }
        if($data){
            $redis->set($id,$data);
        }
    }
    return $data[$field] ?? '账号已注销';
}

function get_old_player($uid)
{
    $redis = new Redis();
    $redis->select(2);
    $data = $redis->get($uid);
    $data = [];
    if(empty($data)){
        $data = DB::connect('db_config_aiqi')->name('player_old')->where(['banma_id'=>$uid])->find();
        if(empty($data)){
            $data = DB::connect('db_config_aiqi')->name('player')
                ->where(array('id'=>$uid,'status'=>1))
                ->find();
            $data['gd_id'] = $data['account'];
        }
        if($data){
            $redis->set($uid,$data);
        }
    }
    return $data['gd_id'] ?? '账号已注销';
}
function get_player_by_account($uid)
{
    $account = get_old_player($uid);
    $redis = new Redis();
    $redis->select(3);
    $account = 'g_'.$account;
    $data = $redis->get($account);
    if(empty($data)){
        $data = DB::connect('db_config_aiqi')->name('player')->where(['account'=>$account])->find();
        if($data){
            $redis->set($account,$data);
        }
    }
    return $data['id'] ?? '账号已注销';
}

function get_channel_player_by_account($uid,$cid)
{
    $redis = new Redis();
    $redis->select(3);
    $account = $cid.'_'.$uid;
    $data = $redis->get($account);
    if(empty($data)){
        $data = DB::connect('db_config_aiqi')->name('player')->where(['account'=>$account])->find();
        if($data){
            $redis->set($account,$data);
        }
    }
    return $data['id'] ?? 0;
}
function get_encrypt($string)
{
    return base64_encode(openssl_encrypt($string, 'AES-128-ECB', env('ENCRYPT_KEY')));
}


function get_decrypt($string)
{
    return openssl_decrypt(base64_decode($string), 'AES-128-ECB', env('ENCRYPT_KEY'));
}

/**
 * 验证验证码
 */
function checkSms($phone, $code){
    $redis = new Redis();
    $redis_code = $redis->get('sms_code_'.$phone);
    if(!$redis_code){
        return false;
    }
    if($code == $redis_code){
        return true;
    }
    return false;
}

/**
 * 生成订单号
 */
function get_order_sn($uid,$gid,$type){
    return $uid.'_'.date('YmdHis').mt_rand(10000,99999);
}

/**
 * 调试用异常信息
 */
function exception_info(\Exception $e) {
    return $e->getFile().'_'.$e->getLine().'_'.$e->getMessage();
}

/**
 * 生成签名
 * @param $data
 * @param $key
 * @return string
 */
function get_sign($data,$key){
    ksort($data);
    $str = '';
    foreach ($data as $k => $v) {
        $str .= $k.'='.$v.'&';
    }
    $str = rtrim($str,'&');
    $strKey = $str.$key;
    Log::info("对接签名字符串：".$strKey);
    return md5($strKey);
}

function get_pay_type($type){
    if($type == 1) {
        return '支付宝';
    }elseif($type == 2){
        return '微信';
    }
    return '渠道支付';
}

function checkName($name)
{
    $ret = true;
    //中文+身份证允许有.
    if (!preg_match('/^[\x{4e00}-\x{9fa5}]+[·•]?[\x{4e00}-\x{9fa5}]+$/u', $name)) {
        return false;
    }
    $strLen = mb_strlen($name);
    if ($strLen < 2 || $strLen > 8) {//字符长度2到8之间
        return false;
    }

    return $ret;
}

/**
 * CURL请求公共方法
 * @param string $url 请求地址
 * @param array|string|null $data 请求数据，数组或字符串
 * @param string $method 请求方式 POST|GET|PUT|DELETE等
 * @param array $headers 请求头，格式如 ['Content-Type: application/json', 'Authorization: Bearer token']
 * @param string $dataType 请求数据格式 json|form
 * @return array 返回响应数据和HTTP状态码
 * @throws Exception
 */
function curlRequest($url, $data = null, $headers = [],  $method = 'POST', $dataType = 'json'){
    $ch = curl_init();
    // 设置基本选项
    $options = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 3,
        CURLOPT_CONNECTTIMEOUT => 30,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ];
    // 设置请求方式
    $method = strtoupper($method);
    if ($method === 'GET') {
        if (!empty($data)) {
            $query = is_array($data) ? http_build_query($data) : $data;
            $options[CURLOPT_URL] .= (strpos($url, '?') !== false ? '&' : '?') . $query;
        }
    } else {
        if ($method !== 'POST') {
            $options[CURLOPT_CUSTOMREQUEST] = $method;
        }
        // 设置请求数据
        if (!empty($data)) {
            if ($dataType === 'json') {
                $postData = is_array($data) ? json_encode($data) : $data;
                $headers[] = 'Content-Type: application/json';
            } else {
                $postData = is_array($data) ? http_build_query($data) : $data;
                $headers[] = 'Content-Type: application/x-www-form-urlencoded';
            }
            $options[CURLOPT_POSTFIELDS] = $postData;
        }
    }
    // 设置请求头
    if (!empty($headers)) {
        $options[CURLOPT_HTTPHEADER] = $headers;
    }
    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if (curl_errno($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception("CURL请求失败: " . $error);
    }

    curl_close($ch);

    return [
        'data' => $response,
        'code' => $httpCode
    ];
}

//用php从身份证中提取生日,包括15位和18位身份证
function getIDCardInfo($IDCard) {
    $result = [
        'error' => 0,      // 0：未知错误，1：身份证格式错误，2：无错误
        'isAdult' => null, // true表示成年，false表示未成年
        'birthday' => '',  // 生日，格式如：2012-11-15
        'age' => null,     // 年龄
        'sex' => '',       // 性别：男/女
    ];

    // 验证18位身份证格式
    if (!preg_match("/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/", $IDCard)) {
        $result['error'] = 1;
        return $result;
    }

    // 提取出生日期
    $birthday = substr($IDCard, 6, 8);
    $year = substr($birthday, 0, 4);
    $month = substr($birthday, 4, 2);
    $day = substr($birthday, 6, 2);

    // 验证日期有效性
    if (!checkdate($month, $day, $year)) {
        $result['error'] = 1;
        return $result;
    }

    // 格式化生日
    $result['birthday'] = "$year-$month-$day";

    // 计算年龄
    $birthDate = new DateTime($result['birthday']);
    $today = new DateTime();
    $age = $today->diff($birthDate)->y;
    $result['age'] = $age;

    // 判断是否成年
    $result['isAdult'] = $age >= 18;

    // 判断性别 (第17位奇数为男，偶数为女)
    $genderCode = substr($IDCard, 16, 1);
    $result['sex'] = ($genderCode % 2 === 1) ? '男' : '女';

    $result['error'] = 2;
    return $result;
}

function aes_cbc_decrypt($ciphertext) {
    $key = "466784a6843584516aef56fcb869ca0c";
    $iv = "d33c735e6cf16b35";
    // 解码base64
    $ciphertext = str_replace("_","/", $ciphertext);
    $ciphertext = str_replace("-","+", $ciphertext);
    $ciphertext = base64_decode($ciphertext);
    // 解密数据
    $plaintext = openssl_decrypt($ciphertext,'AES-256-CBC',$key,OPENSSL_RAW_DATA,$iv);
    if ($plaintext === false) {
        return "解密失败：" . openssl_error_string();
    }
    return $plaintext;
}


function getReportTypeName($type)
{
    $name = [
        "1"=>"充值问题",
        "2"=>"账号问题",
        "3"=>"BUG问题",
        "4"=>"举报问题",
        "5"=>"意见反馈",
    ];
    return $name[$type];
}

function explodeImg($images)
{
    $images = explode(",", $images);
    return $images;

}

function getImgeUrl($url)
{
    $url = $_SERVER['REQUEST_SCHEME']."://{$_SERVER['HTTP_HOST']}/".$url;
    return $url;
}

/**
 * 获取客户端设备类型
 * @return string pc|ios|android
 */
function get_device_type()
{
    $request = $_SERVER;

    $agent = strtolower($request->header('user-agent'));
    if (strpos($agent, 'iphone') || strpos($agent, 'ipad') || strpos($agent, 'ipod')) {
        return 'iOS';
    } elseif (strpos($agent, 'android')) {
        return 'Android';
    }
    return 'PC';
}

//判断客户端是否是在微信客户端打开
function is_weixin(){
    if(empty($_SERVER['HTTP_USER_AGENT'])){
        return false;
    }
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
        return true;
    }
    return false;
}

function get_wx_openid_url()
{
    $data = [
        "appid"=>'wx5f1a667410b75bdf',
        "response_type" => "code",
        "scope" => "snsapi_userinfo",
        "state"=>"aiqi",
    ];
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?".http_build_query($data);
    return $url;
}

function get_wx_config()
{
    $data = [
        "appid"=>'wx5f1a667410b75bdf',
        "timestamp" => time(),
        "nonceStr" => get_noncestr(),
        "signature"=>"aiqi",
        "jsApiList"=>[
            'chooseWXPay'
        ]
    ];
    ksort($data);
    $str = '';
    foreach ($data as $k => $v) {
        $str .= $k.'='.$v.'&';
    }
    $str = rtrim($str,'&');
    return $data;
}
function get_wx_openid($account)
{
    $openid = substr($account, 3);
    return $openid;
}

// 生成随机字符串
function get_noncestr( $length = 32 )
{
    $chars = strtoupper("abcdefghijklmnopqrstuvwxyz0123456789");
    $str ="";
    for ( $i = 0; $i < $length; $i++ )  {
        $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
}

// 是否是法定节假日
function is_hoilday()
{
    $date = date('Y-m-d');
    $data = DB::connect('db_config_aiqi')->name('days')->where(['date'=>$date,'is_holiday'=>1,'is_special'=>1])->find();
    if(!empty($data)){
        return true;
    }
    return true;
}